package com.qf.authserver.config;

import com.qf.authserver.mapper.SysUserMapper;
import com.qf.authserver.pojo.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Component
public class UserSecurityService implements UserDetailsService {
    private static Logger logger = LoggerFactory.getLogger(UserSecurityService.class);
    @Value("${userinfo.path}")
    private String userinfoPath;
    @Resource
    private SysUserMapper sysUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("用户名：" + username);
        SysUser sysUser = sysUserMapper.selectSysUserByUsername(username);
        sysUser.setProfile(userinfoPath + sysUser.getProfile());
        // spring中获取 HttpServletRequest
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        request.getSession().setAttribute("sysuser_info", sysUser);
        return new User(username, sysUser.getPassword(),
                Arrays.asList(new SimpleGrantedAuthority("ROLE_admin")));
    }
}
